/*
 * @lc app=leetcode.cn id=145 lang=cpp
 *
 * [145] 二叉树的后序遍历
 */

#include <limits.h>

#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right)
        : val(x), left(left), right(right) {}
};

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
   public:
    vector<int> postorderTraversal(TreeNode *root) {
        vector<int> ans;
        if (root == nullptr) return ans;

        stack<TreeNode *> tree;
        TreeNode *prev = nullptr;

        while (root != nullptr || !tree.empty()) {
            // 寻找最左子节点
            while (root != nullptr) {
                tree.push(root);
                root = root->left;
            }
            root = tree.top();
            tree.pop();

            // 遍历最左子节点的右子树
            if (root->right == nullptr || root->right == prev) {
                ans.push_back(root->val);
                prev = root;
                root = nullptr;
            } else {
                tree.push(root);
                root = root->right;
            }
        }

        return ans;
    }
};
// @lc code=end
